<!-- components/delivery/DeliveryDialog.vue -->
<template>
  <el-dialog
    v-model="visible"
    :title="isBatch ? '批量发货' : '发货管理'"
    width="600px"
    :before-close="handleClose"
  >
    <div class="delivery-dialog" v-if="orderData">
      <!-- 单个发货 -->
      <div v-if="!isBatch">
        <el-card class="order-summary" shadow="never">
          <div class="order-info">
            <div class="order-id">订单号: {{ orderData.orderInfo.platformOrderId }}</div>
            <div class="customer-name">客户: {{ orderData.customerInfo.name }}</div>
            <div class="order-amount">金额: ¥{{ orderData.orderInfo.amount.toLocaleString() }}</div>
            <div class="order-date">下单时间: {{ orderData.orderInfo.orderDate }}</div>
          </div>
        </el-card>
        
        <el-alert
          v-if="orderData.aiSuggestion"
          :title="orderData.aiSuggestion.content"
          type="info"
          show-icon
          :closable="false"
          class="ai-suggestion-alert"
        />
      </div>
      
      <!-- 批量发货 -->
      <div v-else>
        <el-alert
          title="批量发货"
          type="warning"
          show-icon
          :closable="false"
          class="batch-alert"
        >
          <template #default>
            <p>您将对 {{ batchOrders.length }} 个订单进行发货操作</p>
          </template>
        </el-alert>
      </div>
      
      <!-- 发货表单 -->
      <el-form 
        :model="form" 
        :rules="rules" 
        ref="formRef"
        label-width="100px"
        class="delivery-form"
      >
        <el-form-item label="物流公司" prop="logisticsCompany">
          <el-select v-model="form.logisticsCompany" placeholder="请选择物流公司" filterable>
            <el-option label="顺丰速运" value="顺丰速运" />
            <el-option label="圆通速递" value="圆通速递" />
            <el-option label="中通快递" value="中通快递" />
            <el-option label="韵达快递" value="韵达快递" />
            <el-option label="申通快递" value="申通快递" />
            <el-option label="EMS" value="EMS" />
            <el-option label="京东物流" value="京东物流" />
            <el-option label="德邦物流" value="德邦物流" />
            <el-option label="其他" value="其他" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="物流单号" prop="trackingNumber">
          <el-input
            v-model="form.trackingNumber"
            placeholder="请输入物流单号"
          />
        </el-form-item>
        
        <el-form-item label="发货时间" prop="deliveryDate">
          <el-date-picker
            v-model="form.deliveryDate"
            type="date"
            placeholder="选择发货日期"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        
        <el-form-item label="预计到达" v-if="form.deliveryDate">
          <el-date-picker
            v-model="form.estimatedArrivalDate"
            type="date"
            placeholder="选择预计到达日期"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        
        <el-form-item label="发货备注">
          <el-input
            v-model="form.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入发货备注信息"
          />
        </el-form-item>
      </el-form>
    </div>
    
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
          确认发货
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, computed, reactive, watch } from '@vue/runtime-core'
import type { FormInstance, FormRules } from 'element-plus'
import type { DeliveryOrder } from '../../types/delivery'
import { ElMessage } from 'element-plus'
// 导入API
import { deliveryAPI } from '../../api/delivery'

const props = defineProps<{
  modelValue: boolean
  orderData: DeliveryOrder | null
}>()

const emit = defineEmits<{
  (e: 'update:modelValue', value: boolean): void
  (e: 'success'): void
}>()

const formRef = ref<FormInstance>()
const submitLoading = ref(false)

const visible = computed({
  get: () => props.modelValue,
  set: (value: boolean) => emit('update:modelValue', value)
})

const isBatch = computed(() => {
  return props.orderData?.batchOrders && props.orderData.batchOrders.length > 0
})

const batchOrders = computed(() => {
  return props.orderData?.batchOrders || []
})

const form = reactive({
  logisticsCompany: '',
  trackingNumber: '',
  deliveryDate: '',
  estimatedArrivalDate: '',
  remark: ''
})

const rules = reactive<FormRules>({
  logisticsCompany: [
    { required: true, message: '请选择物流公司', trigger: 'change' }
  ],
  trackingNumber: [
    { required: true, message: '请输入物流单号', trigger: 'blur' }
  ],
  deliveryDate: [
    { required: true, message: '请选择发货日期', trigger: 'change' }
  ]
})

const handleClose = () => {
  visible.value = false
  resetForm()
}

const handleSubmit = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid: boolean) => {
    if (valid) {
      submitLoading.value = true
      try {
        // 调用真实的API
        if (props.orderData) {
          if (isBatch.value) {
            // 批量发货处理
            for (const order of batchOrders.value) {
              // 创建发货记录
              await deliveryAPI.createDeliveryRecord({
                salesOrderId: order.orderInfo.platformOrderId,
                logisticsCompany: form.logisticsCompany,
                trackingNumber: form.trackingNumber,
                deliveryDate: form.deliveryDate,
                estimatedArrivalDate: form.estimatedArrivalDate,
                remark: form.remark,
                status: 'shipped'
              })
              
              // 更新订单发货状态
              await deliveryAPI.updateDeliveryStatus(order.orderInfo.platformOrderId, {
                deliveryStatus: 'shipped',
                logisticsCompany: form.logisticsCompany,
                trackingNumber: form.trackingNumber,
                deliveryDate: form.deliveryDate,
                estimatedArrivalDate: form.estimatedArrivalDate
              })
            }
          } else {
            // 单个发货处理
            // 创建发货记录
            await deliveryAPI.createDeliveryRecord({
              salesOrderId: props.orderData.orderInfo.platformOrderId,
              logisticsCompany: form.logisticsCompany,
              trackingNumber: form.trackingNumber,
              deliveryDate: form.deliveryDate,
              estimatedArrivalDate: form.estimatedArrivalDate,
              remark: form.remark,
              status: 'shipped'
            })
            
            // 更新订单发货状态
            await deliveryAPI.updateDeliveryStatus(props.orderData.orderInfo.platformOrderId, {
              deliveryStatus: 'shipped',
              logisticsCompany: form.logisticsCompany,
              trackingNumber: form.trackingNumber,
              deliveryDate: form.deliveryDate,
              estimatedArrivalDate: form.estimatedArrivalDate
            })
          }
        }
        
        ElMessage.success('发货操作成功')
        emit('success')
        handleClose()
      } catch (error: any) {
        console.error('发货失败:', error)
        ElMessage.error('发货失败: ' + (error.message || '未知错误'))
      } finally {
        submitLoading.value = false
      }
    }
  })
}

const resetForm = () => {
  form.logisticsCompany = ''
  form.trackingNumber = ''
  form.deliveryDate = ''
  form.estimatedArrivalDate = ''
  form.remark = ''
}

// 监听orderData变化，重置表单
watch(() => props.orderData, () => {
  resetForm()
})
</script>

<style scoped>
.delivery-dialog {
  max-height: 500px;
  overflow-y: auto;
}

.order-summary {
  margin-bottom: 16px;
}

.order-info {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 8px;
  font-size: 14px;
}

.order-id, .customer-name, .order-amount, .order-date {
  margin-bottom: 4px;
}

.ai-suggestion-alert, .batch-alert {
  margin-bottom: 16px;
}

.delivery-form {
  margin-top: 16px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}
</style>